﻿using System.Collections.Generic;
using System.Linq;
using Grundy.Common;
using Grundy.Message;

namespace Grundy.Entity
{
    public class FeatureIdentificationKeyMatcher
    {
        private readonly FeatureIdentificationKey _key;
        private readonly FeatureIdentificationKeyMatchScoreEvaluator _matchEvaluator;

        public FeatureIdentificationKeyMatcher(FeatureIdentificationKey key, FeatureIdentificationKeyMatchScoreEvaluator matchEvaluator)
        {
            _key = key;
            _matchEvaluator = matchEvaluator;
        }

        public virtual List<FeatureIdentificationKey> FindMatchingKeys(IEnumerable<FeatureIdentificationKey> keysToSearch)
        {
            if (keysToSearch.IsNullOrEmpty())
            {
                return new List<FeatureIdentificationKey>();
            }

            var scoreList = keysToSearch.Select(i => new { Score = _matchEvaluator.GetMatchScore(_key, i), FeatureIdentificationKey = i })
                            .Where(i => i.Score > 0)
                            .ToList();
                            
            var maxScore = scoreList.Count > 0 ? scoreList.Max(i => i.Score) : 0;

            if (maxScore <= 0)
            {
                return new List<FeatureIdentificationKey>();
            }
            
            var matchingKeys = scoreList.Where(i => i.Score == maxScore).Select(i => i.FeatureIdentificationKey).ToList();
            return matchingKeys;
        }
    }
}